package com.heima.admin.test;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.Test;

import java.util.Date;
import java.util.UUID;

/**
 * @author zhangyan
 * @date 2021/4/23 22:50
 */
public class JWT {

    /**
     * 生成JWT（一般在登录成功后将生成的JWT当做TOKEN来使用）
     */
    @Test
    public void createJwt() {

        String secret = "itcast"; //对称加密密钥

        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, secret)
                .setId(UUID.randomUUID().toString()) //jwt的唯一标识
                .setSubject("测试字符串")
                .setIssuedAt(new Date())//创建时间
                .claim("userName","zhangsan")
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000)) //过期时间
                .compact();

        System.out.println(token);
    }

    /**
     * 解析JWT（用户非登陆请求时校验该用户的token合法性）
     */
    @Test
    public void testParseJwt() {
        String secret = "itcast"; //对称加密密钥
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJjNTYxOTRkZS1jNDdhLTRkOWQtOTNjYy0xN2U1MjdjMjE0ZGIiLCJzdWIiOiLmtYvor5XlrZfnrKbkuLIiLCJpYXQiOjE2MTkxOTAwMzUsInVzZXJOYW1lIjoiemhhbmdzYW4iLCJleHAiOjE2MTkxOTM2MzV9.nYnCmPY2L849gZmk_j2eiLd9AepFMUlNhMircwgXeR0";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(secret).parseClaimsJws(token);

        System.out.println("头：" + claimsJws.getHeader());
        System.out.println("载荷：" + claimsJws.getBody());
        System.out.println("主题：" + claimsJws.getBody().get("sub"));
        System.out.println("userName：" + claimsJws.getBody().get("userName"));
        System.out.println("签名：" + claimsJws.getSignature());
    }

}